<template>
  <div class="login-container">
    <el-card class="login-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h2>用户登录</h2>
        </div>
      </template>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="80px"
        size="large"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="loginForm.email"
            type="email"
            placeholder="请输入邮箱地址"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe">
            记住我
          </el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            :loading="loading"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
        
        <el-form-item>
          <div class="register-link">
            还没有账号？
            <el-link type="primary" @click="goToRegister">立即注册</el-link>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 路由实例
const router = useRouter()

// 响应式数据
const loginFormRef = ref()
const loading = ref(false)

// 表单数据
const loginForm = reactive({
  email: '',
  password: '',
  rememberMe: false
})

// 表单验证规则
const loginRules = reactive({
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
})

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    // 尝试连接后端API
    try {
      const response = await axios.post('http://localhost:8000/api/v1/auth/login', {
        email: loginForm.email,
        password: loginForm.password
      })
      
      if (response.data.success !== false) {
        // 保存用户信息
        const userInfo = response.data.data.user
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        
        // 记住我功能
        if (loginForm.rememberMe) {
          localStorage.setItem('rememberedEmail', loginForm.email)
        } else {
          localStorage.removeItem('rememberedEmail')
        }
        
        ElMessage.success('登录成功！')
        router.push('/')
      } else {
        ElMessage.error(response.data.message || '登录失败')
      }
    } catch (networkError) {
      // 后端服务不可用，使用模拟登录
      console.warn('后端服务不可用，使用模拟登录:', networkError)
      
      // 模拟用户数据（包括测试账号）
      const mockUsers = [
        { email: 'admin@example.com', password: '123456', role: 'admin' },
        { email: 'user1@example.com', password: '123456', role: 'user' },
        { email: 'test@example.com', password: 'test123!', role: 'user' } // 测试账号
      ]
      
      // 验证邮箱和密码
      const user = mockUsers.find(
        u => u.email === loginForm.email && u.password === loginForm.password
      )
      
      if (user) {
        const mockUserData = {
          id: 1,
          username: user.email.split('@')[0],
          email: user.email,
          role: user.role,
          is_active: true,
          avatar_url: null,
          last_login_at: new Date().toISOString(),
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        }
        
        localStorage.setItem('userInfo', JSON.stringify(mockUserData))
        
        // 记住我功能
        if (loginForm.rememberMe) {
          localStorage.setItem('rememberedEmail', loginForm.email)
        } else {
          localStorage.removeItem('rememberedEmail')
        }
        
        ElMessage.success('登录成功（模拟模式）')
        router.push('/')
      } else {
        ElMessage.error('邮箱或密码错误')
      }
    }
  } catch (error) {
    console.error('登录错误:', error)
    if (error.response && error.response.data) {
      ElMessage.error(error.response.data.detail || '登录失败')
    } else {
      ElMessage.error('网络错误，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}

// 初始化记住我功能
const initRememberMe = () => {
  const rememberedEmail = localStorage.getItem('rememberedEmail')
  if (rememberedEmail) {
    loginForm.email = rememberedEmail
    loginForm.rememberMe = true
  }
}

// 组件挂载时初始化
onMounted(() => {
  initRememberMe()
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-card {
  width: 100%;
  max-width: 450px;
  margin: 20px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.register-link {
  text-align: center;
  width: 100%;
}
</style>